package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.config.oss.OssProperties;
import com.ruoyi.common.config.oss.OssTemplate;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.PermitReportFile;
import com.ruoyi.system.entity.SysRemind;
import com.ruoyi.system.mapper.PermitReportFileMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.ViewConfigPushMesMapper;
import com.ruoyi.system.service.PermitReportFileService;
import com.ruoyi.system.service.SysRemindService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 许可证件和报告类型分类管理(PermitReportFile)表服务实现类
 *
 * @author makejava
 * @since 2022-11-18 09:34:20
 */
@Service("permitReportFileService")
public class PermitReportFileServiceImpl implements PermitReportFileService {

    @Autowired
    private OssTemplate template;
    @Autowired
    private OssProperties ossProperties;
    @Resource
    private PermitReportFileMapper permitReportFileDao;

    @Autowired
    private SysRemindService sysRemindService;
    @Resource
    private ViewConfigPushMesMapper viewConfigPushMesMapper;

    @Resource
    private EnterpriseWXServiceImpl enterpriseWXService;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public PermitReportFile queryById(Integer id) {
        return this.permitReportFileDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param permitReportFile 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<PermitReportFile> queryByPage(PermitReportFile permitReportFile, PageRequest pageRequest) {
        long total = this.permitReportFileDao.count(permitReportFile);
        return new PageImpl<>(this.permitReportFileDao.queryAllByLimit(permitReportFile, pageRequest), pageRequest, total);
    }

    @Override
    public List<PermitReportFile> selectList(PermitReportFile permitReportFile) {
        List<PermitReportFile> permitReportFiles = permitReportFileDao.queryAll(permitReportFile);
        if (!CollectionUtils.isEmpty(permitReportFiles)) {
            for (PermitReportFile var : permitReportFiles) {
                if (null == var.getRemindDate()) {
                    var.setColor(0);
                    continue;
                }
                //获取当前时间
                String toDateStr = DateUtils.getDate();
                Date toDate = new Date();

                //获取提醒日期
                String remind = var.getRemindDate();
                Date date = DateUtils.parseDate(remind);

                if (toDateStr.equals(remind)) {
                    var.setColor(1);
                    continue;
                }

                boolean after = toDate.after(date);
                if (after) {
                    var.setColor(2);
                    continue;
                }

                var.setColor(0);
            }
        }
        return permitReportFiles;
    }

    /**
     * 新增数据
     *
     * @param permitReportFile 实例对象
     * @return 实例对象
     */
    @Override
    public PermitReportFile insert(PermitReportFile permitReportFile) {
        permitReportFile.setCreatedDate(DateUtils.getNowDate());
        this.permitReportFileDao.insert(permitReportFile);
        return permitReportFile;
    }

    /**
     * 修改数据
     *
     * @param permitReportFile 实例对象
     * @return 实例对象
     */
    @Override
    public PermitReportFile update(PermitReportFile permitReportFile) {
        this.permitReportFileDao.update(permitReportFile);
        return this.queryById(permitReportFile.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Integer id) {
        PermitReportFile permitReportFile = permitReportFileDao.queryById(id);
        if (null != permitReportFile) {
            if (StringUtils.isNotBlank(permitReportFile.getReportFileName())) {
                try {
                    template.removeObject(ossProperties.getBucketName(), permitReportFile.getReportFileName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(permitReportFile.getPermitFileName())) {
                try {
                    template.removeObject(ossProperties.getBucketName(), permitReportFile.getPermitFileName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return this.permitReportFileDao.deleteById(id) > 0;
    }

    @Scheduled(cron = "0 0 8 * * ?")
    public void checkPermitReportFile() {
        PermitReportFile permitReportFile = new PermitReportFile();
        permitReportFile.setType(1);
        List<PermitReportFile> relateds = permitReportFileDao.queryAll(permitReportFile);
        if (CollectionUtils.isEmpty(relateds)) {
            return;
        }

        for (PermitReportFile var : relateds) {
            String remind = var.getRemindDate();
            Date date = new Date();
            boolean after = date.after(DateUtils.parseDate(remind));
            if (after) {
                String card = null;
                if (StringUtils.isEmpty(var.getCardNumber())) {
                    card = var.getCard();
                } else {
                    card = var.getCardNumber();
                }
                String stringBuffer = "许可证证件名称:" + var.getPermitFileName() +
                        "编号:" + card + "即将到期。";

               /* ViewConfigPushMes viewConfigPushMes = new ViewConfigPushMes();
                viewConfigPushMes.setViewName("安全许可证信息");
                List<ViewConfigPushMes> configPushMes = viewConfigPushMesMapper.queryByViewKey(viewConfigPushMes);
                if (!CollectionUtils.isEmpty(configPushMes)) {
                    ViewConfigPushMes pushMes = configPushMes.stream().findFirst().orElse(new ViewConfigPushMes());
                    if (com.ruoyi.common.utils.StringUtils.isNotEmpty(pushMes.getViewValue())) {
                        boolean contains = pushMes.getViewValue().contains(",");
                        if (contains) {
                            String[] split = pushMes.getViewValue().split(",");
                            for (String vars : split) {
                                sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, Integer.valueOf(vars));
                            }
                        } else {
                            sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, Integer.valueOf(pushMes.getViewValue()));
                        }
                    }
                }*/

                SysRole sysRole = new SysRole();
                sysRole.setRoleKey("sbjyts");
                List<SysUser> sysUsers = sysUserMapper.selectUserByRoleName(sysRole);
                if (CollectionUtils.isEmpty(sysUsers)) {
                    return;
                }

                for (SysUser sys : sysUsers) {
                    sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, sys.getUserId().intValue());
                }

                List<String> collect = sysUsers.stream().map(SysUser::getWxUserId).collect(Collectors.toList());
                EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
                sendMessageRequest.setTouser(CollUtil.join(collect, "|"));
                sendMessageRequest.setMsgtype("text");
                sendMessageRequest.setAgentid(1000319);
                EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
                messageContent.setContent(stringBuffer);
                sendMessageRequest.setText(messageContent);
                enterpriseWXService.pushMessage(sendMessageRequest);
            }
        }
    }


}
